package structure.likedList;

/**
 * Java实现单链表
 */
public class SingleLinkedList {

    private int size;
    private Node head;

    public SingleLinkedList() {
        size = 0;
    }

    // 头部加
    public void addHead(Integer value) {
        Node node = new Node(value);
        if (head == null) {
            head = node;
        }
        node.next = head;
        head = node;
        size++;
    }

    // 尾部加
    public void addTail(Integer value) {
        Node node = new Node(value);
        if (head == null) {
            head = node;
        }
        Node last = head;
        while (last.next != null) {
            last = last.next;
        }
        last.next = node;
        size++;
    }

    // 删除，默认删除头
    public void del() {
        if (head == null) {
            return;
        }
        head = head.next;
        size--;
    }

    public Node findByValue(Integer value) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        while (cur != null) {
            if (cur.value.equals(value)) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    public Node findByIndex(Integer index) {
        if (head == null) {
            return null;
        }
        Integer count = 0;
        Node cur = head;
        while (count < index && cur != null) {
            cur = cur.next;
            count++;
        }
        return cur;
    }

    // bug 没有处理size 没处理index=0的情况
    public void delete(Integer index) {
        if (index < 0 || index > size - 1) {
            return;
        }
        Node cur = head;
        int count = 0;
        while (cur != null && cur.next != null) {
            if (count == index - 1) {
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
            count++;
        }
    }

    // 没有处理 index=0的情况
    public void insert(Integer index, Integer value) {
        Node node = new Node(value);
        int count = 0;
        Node cur = head;
        while (count < index - 1) {
            cur = cur.next;
            count++;
        }

        node.next = cur.next;
        cur.next = node;
        size++;
    }

    public Node reverse(Node node) {
        Node pre = null;
        Node next = null;
        while (node != null) {
            // 暂存
            next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }

    private static class Node {
        private final Integer value;
        private Node next;

        private Node(Integer value) {
            this.value = value;
        }
    }
}
